import datetime
from typing import Dict, Any

from bson import ObjectId
from pydantic import BaseModel as _BaseModel, Field, validator, field_validator


class BaseModel(_BaseModel):
    class Config:
        arbitrary_types_allowed = True  # 允许任意类型(可自定义)
        validate_assignment = True  # 赋值验证


class DBModel(_BaseModel):
    create_time: datetime.datetime = Field(default_factory=datetime.datetime.now)
    id: ObjectId = Field(None, alias='_id')  # 可选的mongoid

    class Config:
        arbitrary_types_allowed = True  # 允许任意类型(可自定义)

    def dict(self, *args, **kwargs) -> Dict[str, Any]:
        """mongodb, 如果没有设置_id, 让数据库自动插入"""
        res = super().dict(*args, **kwargs)
        if '_id' in res and res['_id'] is None:
            res.pop('_id')
        return res
